package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.feigns.admin.AdminFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {
    @Autowired
    ApArticleMapper apArticleMapper;
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {
        //1 查询前五天已上架/未删除的文章
        String date = DateTime.now().minusDays(5).toString("yyyy-MM-dd 00:00:00");
        List<ApArticle> articleList = apArticleMapper.selectList(Wrappers.<ApArticle>lambdaQuery().gt(ApArticle::getPublishTime, date));
        //2 计算热点文章分值
        List<HotArticleVo> hotArticleVoList = computeArticleScore(articleList);
        //3  每个频道缓存30条数据
        cacheTagToRedis(hotArticleVoList);
    }

    /**
     * 每个频道缓存30条数据
     *
     * @param hotArticleVoList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        //查询所有的频道列表
        List<AdChannel> allChannels = adminFeign.findAllChannels();

        for (AdChannel channel : allChannels) {
            //获取每个频道对应的数据
            List<HotArticleVo> hotArticleVos = hotArticleVoList.stream()
                    .filter(hotArticle -> hotArticle.getChannelId().equals(channel.getId()))
                    .collect(Collectors.toList());
            //缓存此频道的热点文章
            sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + channel.getId());
        }

        //缓存推荐频道的热点文章
        sortAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 缓存热点文章
     *
     * @param hotArticleVos
     * @param key
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String key) {
        //文章按分数排序
        hotArticleVos = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .limit(30).collect(Collectors.toList());
        //存入redis
        redisTemplate.opsForValue().set(key, JSON.toJSONString(hotArticleVos));
    }

    /**
     * 计算热点文章分值
     *
     * @param articleList
     * @return
     */
    private List<HotArticleVo> computeArticleScore(List<ApArticle> articleList) {
        ArrayList<HotArticleVo> hotArticleVoList = new ArrayList<>();
        //遍历封装数据vo
        for (ApArticle apArticle : articleList) {
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle, hotArticleVo);
            //文章分值计算
            Integer score = computeScore(apArticle);
            hotArticleVo.setScore(score);
            hotArticleVoList.add(hotArticleVo);
        }
        return hotArticleVoList;
    }

    /**
     * 分值计算
     *
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        //阅读分数 1
        if (apArticle.getViews() != null) {
            score += apArticle.getViews() * ArticleConstants.HOT_ARTICLE_VIEW_WEIGHT;
        }
        //点赞分数 3
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        //评论分数 5
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        //收藏分数 8
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return score;
    }
}
